package com.jt.www.job.woxuebao;

import com.jt.www.biz.pay.service.PayOutService;
import com.jt.www.model.woxuebao.PayOutEntity;
import com.jt.www.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 我学保支付超时检查
 *
 * @author shaoyn
 */
@Component
@EnableScheduling
public class CheckPayOutTask implements SchedulingConfigurer {

    public static final Logger log = LoggerFactory.getLogger(CheckPayOutTask.class);
    /**
     * 我学保批量投保  检查到账确认 缓存key
     */
    private static final String PAYOUT_LOCK_KEY = "EDU_PAYOUT";
    @Autowired
    PayOutService payOutService;
    /**
     * 任务开关
     */
    @Value("${jtpf.payout.open}")
    private int checkOpen;
    /**
     * 任务执行周期
     */
    @Value("${jtpf.payout.cron}")
    private String cron;// 每隔2分钟执行一次

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        if (checkOpen != 1) {
            return;
        }
        Runnable task0 = () -> checkStart();
        Trigger trigger0 = triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext);
        taskRegistrar.addTriggerTask(task0, trigger0);
    }

    private void checkStart() {
        if (!RedisUtil.setLock(PAYOUT_LOCK_KEY)) {
            return;
        }
        log.info("检查支付超时任务开始执行");
        try {
            //得到需要检查的集合
            List<PayOutEntity> list = payOutService.getNeedVerifyList();
            //检查及处理支付超时集合
            payOutService.processPayOut(list);
        } catch (Exception e) {
            log.info("检查支付超时任务异常", e);
        } finally {
            //删除缓存
            RedisUtil.delete(PAYOUT_LOCK_KEY);
            log.info("我学保批量投保(到账确认)任务结束!");
        }
        log.info("检查支付超时任务执行结束");
    }

}
